# coding:utf-8
from scapy.all import *
from catch_logging import CatchLogging


# 抓包
class CatchBag(object):

    # 网卡名称
    __iface_str = ''
    # 过滤规则
    __filter_str = ''
    # 抓包后的回调函数
    __callback = None

    def __init__(self, iface_str, filter_str):
        self.__iface_str = iface_str
        self.__filter_str = filter_str

    def sniff(self, callback):
        self.__callback = callback
        # count等0表示一直监听，要想监听数据包，需要首先安装winpcap
        print('start catch')
        sniff(filter=self.__filter_str, prn=self.__sniff_callback, iface=self.__iface_str, count=0)

    def __sniff_callback(self, p):
        res = None
        try:
            summary = p.summary()
            udp = 'UDP' in summary
            tcp = 'TCP' in summary
            ipv6 = 'IPv6' in summary
            # 只获取UDP和TCP的ipv4数据
            if (udp or tcp) and not ipv6:
                res = re.findall('((\d{1,3}\.){3}\d{1,3})', summary)
                if len(res) != 2:
                    return
                src_ip = res[0][0]
                des_ip = res[1][0]
                s = ""
                x = bytes_encode(p)
                x_len = len(x)
                i = 0
                while i < x_len:
                    for j in range(16):
                        if i + j < x_len:
                            s += "%02X " % orb(x[i + j])
                        else:
                            s += "   "
                    i += 16
                s = s[:-1] if s.endswith("\n") else s
                data_type = 'udp' if udp else 'tcp'
                res = {
                    'srcIp': src_ip,
                    'destIp': des_ip,
                    'msgStr': s,
                    'dataType': data_type,
                    'summary': summary
                }
        except Exception as e:
            CatchLogging.error(e.message)
        self.__callback(res)






